package com.example.demo.configuration.inter;

import com.example.demo.SpringUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;

@Component
public class CustomNullSerializer extends StdSerializer<Object> {


    private CustomNullSerializer() {
        super(Object.class);
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        Object objValue = gen.getCurrentValue();
        String fieldName = gen.getOutputContext().getCurrentName();
        ShowRuleHandler showRuleHandler = SpringUtils.getBean(ShowRuleHandler.class);
        String typCode = showRuleHandler.getTypeCodeValue(objValue);
        //无意义值展示处理
        String invalidValue = showRuleHandler.getInvalidValue(typCode, fieldName);
        if(invalidValue != null){
            gen.writeString(invalidValue);
            return;
        }
        //默认值处理
        BigDecimal defaultZeroValue = showRuleHandler.getDefaultZeroValue(fieldName, value);
        if(defaultZeroValue != null){
            gen.writeNumber(defaultZeroValue);
            return;
        }
        gen.writeNull();
    }

    /**
     * Although this method should rarely get called, for convenience we should override
     * it, and handle it same way as "natural" types: by serializing exactly as is,
     * without type decorations. The most common possible use case is that of delegation
     * by JSON filter; caller cannot know what kind of serializer it gets handed.
     */
    @Override
    public void serializeWithType(Object value, JsonGenerator gen, SerializerProvider serializers,
                                  TypeSerializer typeSer)
            throws IOException {
        gen.writeNull();
    }

    @Override
    public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException {
        return createSchemaNode("null");
    }

    @Override
    public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException {
        visitor.expectNullFormat(typeHint);
    }


}
